<?php
function display_order($table) {
	$_POST ['id'] = intval ( $_POST ['id'] );
	$_POST ['baseid'] = intval ( $_POST ['baseid'] );
	if ($_POST ['id'] <= 0 || $_POST ['baseid'] <= 0) {
		echo 0;
		exit ();
	}
	
	$map ['id'] = array (
			'in',array ($_POST ['id'],$_POST ['baseid'] ) 
	);
	$res = M ( $table )->where ( $map )->field ( 'id,display_order' )->select ();
	if (count ( $res ) < 2) {
		echo 0;
		exit ();
	}
	foreach ( $res as $v ) {
		$order [$v ['id']] = intval ( $v ['display_order'] );
	}
	unset ( $res );
	$res = M ( $table )->where ( '`id`=' . $_POST ['id'] )->setField ( 'display_order', $order [$_POST ['baseid']] );
	$res = $res && M ( $table )->where ( '`id`=' . $_POST ['baseid'] )->setField ( 'display_order', $order [$_POST ['id']] );
	if ($res)
		echo 1;
	else
		echo 0;
}
function read_file($filename) {
	$content = '';
	if (function_exists ( 'file_get_contents' )) {
		@$content = file_get_contents ( $filename );
	} else {
		if (@$fp = fopen ( $filename, 'r' )) {
			@$content = fread ( $fp, filesize ( $filename ) );
			@fclose ( $fp );
		}
	}
	return $content;
}
function getPage($count,$pagesize,$tag,$nowPage,$url,$prex,$text) {
	$rollPage = 5;
	if ($count < $pagesize)
		return;
		// 总页数
	$totalPages = ceil ( $count / $pagesize );
	// 分页栏的总页数
	$coolPages = ceil ( $totalPages / $rollPage );

	if (! empty ( $totalPages ) && $nowPage > $totalPages) {
		$nowPage = $totalPages;
	}
	// 起始页
	$firstRow = $pagesize * ($nowPage - 1);
	// 当前分页栏页数
	$nowCoolPage = ceil ( $nowPage / $rollPage );
	$parameter = '';
	// 向上翻
	$upRow = $nowPage - 1;
	// 向下翻
	$downRow = $nowPage + 1;
	
	$parseStr = '';
	if (isset ( $tag ) && ! empty ( $tag )) {
		// 总数
		if (strtolower ( $tag ) == 'totalnum') {
			$parseStr .= '共' . $count . '条数据&nbsp;';
		}
		// 首页
		if (strtolower ( $tag ) == 'firstpage') {
			$text = empty($text)?'首页':$text;
			if ($nowPage == 1) {
				$parseStr .= $text.'&nbsp;';
			} else {
				$parseStr .= "<a href='".$url.'.'.$prex."'>".$text."</a>&nbsp;";
			}
			if ($nowCoolPage != 1) {
				$preRow = $nowPage - $rollPage;
				if($preRow == 1)
					$parseStr .= "<a href='".$url.'.'.$prex."'>上".$rollPage."页</a>";
				else
					$parseStr .= "<a href='".$url."-".$preRow.'.'.$prex."'>上".$rollPage."页</a>";
			}
		}
		// 上一页
		if (strtolower ( $tag ) == 'previouspage') {
			$text = empty($text)?'上一页':$text;
			if ($upRow > 0) {
				if($upRow == 1)
					$parseStr .= "<a href='".$url.'.'.$prex."'>".$text."</a>";
				else
					$parseStr .= "<a href='".$url."-".$upRow.'.'.$prex."'>".$text."</a>";
			} else {
				$parseStr .= $text;
			}
		}
		// 显示数字
		if (strtolower ( $tag ) == 'pagenavigation') {
			for($i = 1; $i <= $rollPage; $i ++) {
				$page = ($nowCoolPage - 1) * $rollPage + $i;
				if ($page != $nowPage) {
					if($page == 1) {
						$parseStr .= "&nbsp;<a href='".$url.'.'.$prex."'>".$page."&nbsp;</a>";
					} elseif ($page <= $totalPages) {
						$parseStr .= "&nbsp;<a href='".$url."-".$page.'.'.$prex."'>".$page."&nbsp;</a>";
					} else {
						break;
					}
				} else {
					if ($totalPages != 1) {
						$parseStr .= "&nbsp;<span class='current'>" . $page."&nbsp;</span>";
					}
				}
			}
		}
		// 下一页
		if (strtolower ( $tag ) == 'nextpage') {
			$text = empty($text)?'下一页':$text;
			if ($downRow <= $totalPages) {
				$parseStr .= "<a href='".$url."-".$downRow.'.'.$prex."'>".$text."</a>&nbsp;";
			} else {
				$parseStr .= $text.'&nbsp;';
			}
		}
		// 最后一页
		if (strtolower ( $tag ) == 'lastpage') {
			$text = empty($text)?'最后一页':$text;
			if ($nowCoolPage == $coolPages) {
			} else {
				$nextRow = $nowPage + $rollPage;
				if($nextRow > $totalPages) {
					
				} else {
					$parseStr .= "<a href='".$url."-".$nextRow.'.'.$prex."'>下".$rollPage."页</a>&nbsp;";
				}
			}
			if ($nowPage == $totalPages) {
				$parseStr .= $text.'&nbsp;';
			} else {
				$parseStr .= "<a href='".$url."-".$totalPages.'.'.$prex."'>".$text."&nbsp;</a>";
			}
		}

        //当前页
        if(strtolower($tag) == 'currentpageindex') {
            $parseStr .= '当前第'.$nowPage.'页';
        }

		// 跳转到
		if (strtolower ( $tag ) == 'jumppage') {
			$text = empty($text)?'跳转到':$text;
			$parseStr .= $text . ":<select onChange='javascript:window.location.href=(this.options[this.selectedIndex].value);'>";
			for($i = 1; $i <= $totalPages; $i ++) {
				if ($i == $nowPage) {
					$parseStr .= "<a>" . $i . "</a>";
					$parseStr .= "<option value='".$url."-".$i.'.'.$prex."' selected='selected'>".$i."</option>";
				} else {
					if($i == 1) {
						$parseStr .= "<option value='".$url.'.'.$prex."'>".$i."</option>";
					} else {
						$parseStr .= "<option value='".$url."-".$i.'.'.$prex."'>".$i."</option>";
					}
				}
			}
			$parseStr .= '</select>';
		}
	}
	return $parseStr;
}
/**
 * 图片保存本地
 * @param string $savepath 图片保存路径
 * @param string $pathrule 上传文件目录规则
 * @param int $uid 用户ID
 * @param int $id 相册ID
 */
function uploadPic2($savepath,$code) {
	if (! empty ( $_FILES ) && !empty($_FILES['imageurl']['name'])) {
		import ( "ORG.Net.UploadFile" );
		$upload = new UploadFile ();
		// 设置上传文件大小
		$upload->maxSize = 5 * 1000000;
		// 设置上传文件类型
		$upload->allowExts = array('jpg', 'gif', 'png', 'jpeg','bmp');;
		// 设置附件上传目录
		$upload->savePath = $savepath;
		$upload->saveRule = $code;
		mkdir ( $upload->savePath, 0777, true );
		if (! $upload->upload ()) {
			// 捕获上传异常
			echo $upload->getErrorMsg ();
			exit ();
		} else {
			$fileinfo = $upload->getUploadFileInfo (); // 得到已上传文件的信息数组
		}
		return $fileinfo;
	} else {
		return false;
	}
}
//排序
function cmp_func($a, $b) {
	global $order;
	if ($a['is_dir'] && !$b['is_dir']) {
		return -1;
	} else if (!$a['is_dir'] && $b['is_dir']) {
		return 1;
	} else {
		if ($order == 'size') {
			if ($a['filesize'] > $b['filesize']) {
				return 1;
			} else if ($a['filesize'] < $b['filesize']) {
				return -1;
			} else {
				return 0;
			}
		} else if ($order == 'type') {
			return strcmp($a['filetype'], $b['filetype']);
		} else {
			return strcmp($a['filename'], $b['filename']);
		}
	}
}
/**
 * kindeditor图片、视频、swf上传
 * @param string $save_path 图片保存路径
 * @param string $save_url 文件保存目录URL
 */
function uploadPic($save_path,$save_url,$dirname, $saveFileName=true) {
	//$php_url = dirname($_SERVER['PHP_SELF']) . '/';
	if (!file_exists($save_path)) {
		mk_dir($save_path);
	}
	$php_url = './';
	$save_url = $php_url .$save_url;
	//定义允许上传的文件扩展名
	$ext_arr = array(
			'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
			'flash' => array('swf', 'flv'),
			'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
			'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
	);
	//最大文件大小
	$max_size = 10000000;
	$save_path = realpath($save_path) . '/';
	//PHP上传失败
	if (!empty($_FILES['imgFile']['error'])) {
		switch($_FILES['imgFile']['error']){
			case '1':
				$error = '超过php.ini允许的大小。';
				break;
			case '2':
				$error = '超过表单允许的大小。';
				break;
			case '3':
				$error = '图片只有部分被上传。';
				break;
			case '4':
				$error = '请选择图片。';
				break;
			case '6':
				$error = '找不到临时目录。';
				break;
			case '7':
				$error = '写文件到硬盘出错。';
				break;
			case '8':
				$error = 'File upload stopped by extension。';
				break;
			case '999':
			default:
				$error = '未知错误。';
		}
		echo json_encode(array('error' => 1, 'message' => $error));
		exit;
	}
	//有上传文件时
	if (empty($_FILES) === false) {
		//原文件名
		$file_name = $_FILES['imgFile']['name'];
		//服务器上临时文件名
		$tmp_name = $_FILES['imgFile']['tmp_name'];
		//文件大小
		$file_size = $_FILES['imgFile']['size'];
		//检查文件名
		if (!$file_name) {
			echo json_encode(array('error' => 1, 'message' => "请选择文件。"));
			exit;
		}
		//检查目录
		if (@is_dir($save_path) === false) {
			echo json_encode(array('error' => 1, 'message' => "上传目录不存在。"));
			exit;
		}
		//检查目录写权限
		if (@is_writable($save_path) === false) {
			echo json_encode(array('error' => 1, 'message' => "上传目录没有写权限。"));
			exit;
		}
		//检查是否已上传
		if (@is_uploaded_file($tmp_name) === false) {
			echo json_encode(array('error' => 1, 'message' => "上传失败。"));
			exit;
		}
		//检查文件大小
		if ($file_size > $max_size) {
			echo json_encode(array('error' => 1, 'message' => "上传文件大小超过限制。"));
			exit;
		}
		//获得文件扩展名
		$temp_arr = explode(".", $file_name);
		$file_ext = array_pop($temp_arr);
		$file_ext = trim($file_ext);
		$file_ext = strtolower($file_ext);
		//检查目录名
		if(!empty($dirname))
					$dir_name = $dirname;
		else {
            if ($saveFileName) {
                $dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);
                if (empty($ext_arr[$dir_name])) {
                    echo json_encode(array('error' => 1, 'message' => "目录名不正确。"));
                    exit;
                }
                //检查扩展名
                if (in_array($file_ext, $ext_arr[$dir_name]) === false) {
                    echo json_encode(array('error' => 1, 'message' => "上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。"));
                    exit;
                }
            }
		}
		
		$configfilepath='/apps/cms/Conf/yunconfig.php';
		$isopenyun = service("Xattach") -> isOpenYun($configfilepath);
		if($isopenyun){
			$file_url = service("Xattach") -> uploadUpYun($dir_name,$configfilepath);
			if($file_url === false){
				echo json_encode(array('error' => 1, 'message' => "上传文件失败。"));
				exit;
			}
		}else{
			//创建文件夹
			if ($dir_name !== '') {
				$save_path .= $dir_name . "/";
				$save_url .= $dir_name . "/";
				if (!file_exists($save_path)) {
					mkdir($save_path);
				}
			}
            if ($saveFileName) {
                $ymd = date("Ymd");
                $save_path .= $ymd . "/";
                $save_url .= $ymd . "/";
                if (!file_exists($save_path)) {
                    mkdir($save_path);
                }
                //新文件名
                $new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
            } else {
                $new_file_name = 'templatePic.'.$file_ext;
            }


			//移动文件
			$file_path = $save_path . $new_file_name;
			if (move_uploaded_file($tmp_name, $file_path) === false) {
				echo json_encode(array('error' => 1, 'message' => "上传文件失败。"));
				exit;
			}
			@chmod($file_path, 0644);
            if ($saveFileName) {
                $file_url = $save_url . $new_file_name;
            } else {
                $file_url = $new_file_name;
            }
		}
		
		header('Content-type: text/html; charset=UTF-8');
		echo json_encode(array('error' => 0, 'url' => $file_url));
		exit;
	}
}
/**
 * kindeditor获取服务器上的图片
 * @param string $save_path 图片保存路径
 * @param string $save_url 文件保存目录URL
 */
function getServerPic($root_path,$root_url) {
	$php_url =  './';
	$root_url = $php_url .$root_url;
	//图片扩展名
	$ext_arr = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
	//目录名
	$dir_name = empty($_GET['dir']) ? '' : trim($_GET['dir']);
	if (!in_array($dir_name, array('', 'image', 'flash', 'media', 'file'))) {
		echo "Invalid Directory name.";
		exit;
	}
	if ($dir_name !== '') {
		$root_path .= $dir_name . "/";
		$root_url .= $dir_name . "/";
		if (!file_exists($root_path)) {
			mkdir($root_path);
		}
	}
	//根据path参数，设置各路径和URL
	if (empty($_GET['path'])) {
		$current_path = realpath($root_path) . '/';
		$current_url = $root_url;
		$current_dir_path = '';
		$moveup_dir_path = '';
	} else {
		$current_path = realpath($root_path) . '/' . $_GET['path'];
		$current_url = $root_url . $_GET['path'];
		$current_dir_path = $_GET['path'];
		$moveup_dir_path = preg_replace('/(.*?)[^\/]+\/$/', '$1', $current_dir_path);
	}
	echo realpath($root_path);
	//排序形式，name or size or type
	$order = empty($_GET['order']) ? 'name' : strtolower($_GET['order']);
	$GLOBALS['order'] = $order;
	//不允许使用..移动到上一级目录
	if (preg_match('/\.\./', $current_path)) {
		echo 'Access is not allowed.';
		exit;
	}
	//最后一个字符不是/
	if (!preg_match('/\/$/', $current_path)) {
		echo 'Parameter is not valid.';
		exit;
	}
	//目录不存在或不是目录
	if (!file_exists($current_path) || !is_dir($current_path)) {
		echo 'Directory does not exist.';
		exit;
	}
	//遍历目录取得文件信息
	$file_list = array();
	if ($handle = opendir($current_path)) {
		$i = 0;
		while (false !== ($filename = readdir($handle))) {
			if ($filename{0} == '.') continue;
			$file = $current_path . $filename;
			if (is_dir($file)) {
				$file_list[$i]['is_dir'] = true; //是否文件夹
				$file_list[$i]['has_file'] = (count(scandir($file)) > 2); //文件夹是否包含文件
				$file_list[$i]['filesize'] = 0; //文件大小
				$file_list[$i]['is_photo'] = false; //是否图片
				$file_list[$i]['filetype'] = ''; //文件类别，用扩展名判断
			} else {
				$file_list[$i]['is_dir'] = false;
				$file_list[$i]['has_file'] = false;
				$file_list[$i]['filesize'] = filesize($file);
				$file_list[$i]['dir_path'] = '';
				$file_ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
				$file_list[$i]['is_photo'] = in_array($file_ext, $ext_arr);
				$file_list[$i]['filetype'] = $file_ext;
			}
			$file_list[$i]['filename'] = $filename; //文件名，包含扩展名
			$file_list[$i]['datetime'] = date('Y-m-d H:i:s', filemtime($file)); //文件最后修改时间
			$i++;
		}
		closedir($handle);
	}
	usort($file_list, 'cmp_func');
	$result = array();
	//相对于根目录的上一级目录
	$result['moveup_dir_path'] = $moveup_dir_path;
	//相对于根目录的当前目录
	$result['current_dir_path'] = $current_dir_path;
	//当前目录的URL
	$result['current_url'] = $current_url;
	//文件数
	$result['total_count'] = count($file_list);
	//文件列表数组
	$result['file_list'] = $file_list;
	echo json_encode($result);
}

function preg_parse($html, $attr) {
    preg_match_all('/<'.$attr.'(.*?)<\/'.$attr.'>/eis', $html, $matches);
    return $matches[0];
}

function getParseOneAttr($matches, $name) {
    preg_match ('/'.$name.'=("|\')(.*?)\1/eis', $matches, $split);
    return $split[2];
}

function getParseContentText($html, $attr) {
    preg_match_all('/<'.$attr.'(.*?)>(.*?)<\/'.$attr.'>/eis', $html, $matchquery);
    return trim($matchquery[2][0]);
}

/**
 * 获取匹配的标签的属性字符串
 * @param type $html 待匹配的字符串
 * @param type $attr 标签名，如：yl:contents
 */
function getParseAttrString($html, $attr){
    preg_match_all('/<'.$attr.'(.*?)>(.*?)<\/'.$attr.'>/eis', $html, $matchquery);
    return trim($matchquery[1][0]);
}
// 文件拷贝
function recurse_copy($src, $dst) {
    $dir = opendir($src);
    @mkdir($dst);
    while(false !== ( $file = readdir($dir)) ) {
        if (( $file != '.' ) && ( $file != '..' )) {
            if ( is_dir($src . '/' . $file) ) {
                recurse_copy($src . '/' . $file,$dst . '/' . $file);
            }
            else {
                copy($src . '/' . $file,$dst . '/' . $file);
            }
        }
    }
    closedir($dir);
}

function showCreatePage($id, $sid, $cid) {
    // 内容是否存在外链
    $url = M('cms_article')->where(array('id' => $id))->getField('url');
    if ($url) {
        return $url;
    } else {
        // 获取站点目录
        $dirname = M('cms_site')->where(array('siteid' => $sid))->getField('dirname');
        // 获取内容的命名规则
        $artnaming = M('cms_category')->where(array('id' => $cid))->getField('artnaming');

        if (empty($artnaming)) {
            $changeStyle = model('Data')->get('cmsconfig:site-'.$sid);
            $artnaming = $changeStyle['artnaming'];
        }

        $artnaming = str_replace('{@ChannelID}', $cid, $artnaming);
        $artnaming = str_replace('{@ContentID}', $id, $artnaming);
        $artnaming = str_replace('{@Year}', date("Y"), $artnaming);
        $artnaming = str_replace('{cateid}', $cid, $artnaming);
        $artnaming = str_replace('{contentid}', $id, $artnaming);

        return $dirname . '/'. $artnaming;
    }
}

function tree($arr, $pid = 0, $name) {
    $tree = array();
    foreach($arr as $key => $value) {
    	if ($value['pid'] == $pid) {
    		if ($value['pid'] == 0) {
    			$value['text'] = $name[$key];
    		} else {
    			$value['text'] = $value['cname'];
    		}
    		$value['id'] = intval($value['id']);
    		$value['sid'] = intval($value['sid']);
    		$value['count'] = intval($value['count']);
    		
    		unset($value['pid']);
    		unset($value['cname']);
    		foreach ($arr as $subvalue) {
    			if ($subvalue['pid'] == $value['id']) {
    				$value['children'] = tree($arr, $value['id']);
    				break;
    			}
    		}
    		$tree[] = $value;
    	}
    }
    return $tree;
}

// 获取文章类型
function get_article_type($type = null){
    if(!isset($type)){
        return false;
    }
    switch ($type){
    	case 0  : return    '导入'; break;
        case 1  : return    '文章'; break;
        case 2  : return    '视频'; break;
        case 3  : return    '图片'; break;
        default : return    false;  break;
    }
}


//站内链接转换
function text2Url($content){
	$config = include SITE_PATH .'/apps/cms/Conf/textlink.php' ;
	if (!$config) {
		return  null ;
	}
	$openlink   = $config['openlink'];   // 是否开启
	$openkeword = $config['openkeword']; //是否设置栏目为关键字
	$linkcode   = $config['linkcode'];   //链接内容
	$linkmun    = $config['linknum'];    //替换次数
	
	
	$textlink = model( 'textlink')->find();
	foreach($textlink  as $link){
		$url=str_replace($linkcode, $link['url' ], '{0}' );
		$url=str_replace($url, $link[ 'text'], '{1}');
		$max_count = substr_count($content,$link[ 'text']);
		

	}
	 
	 
}

/**
 +----------------------------------------------------------
 * 产生随机字串，可用来自动生成密码 默认长度6位 字母和数字混合
 +----------------------------------------------------------
 * @param string $len 长度
 * @param string $type 字串类型
 * 0 字母 1 数字 其它 混合
 * @param string $addChars 额外字符
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function rand_string($len=6,$type='',$addChars='') {
    $str ='';
    switch($type) {
        case 0:
            $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.$addChars;
            break;
        case 1:
            $chars= str_repeat('0123456789',3);
            break;
        case 2:
            $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ'.$addChars;
            break;
        case 3:
            $chars='abcdefghijklmnopqrstuvwxyz'.$addChars;
            break;
        case 4:
            $chars = "们以我到他会作时要动国产的一是工就年阶义发成部民可出能方进在了不和有大这主中人上为来分生对于学下级地个用同行面说种过命度革而多子后自社加小机也经力线本电高量长党得实家定深法表着水理化争现所二起政三好十战无农使性前等反体合斗路图把结第里正新开论之物从当两些还天资事队批点育重其思与间内去因件日利相由压员气业代全组数果期导平各基或月毛然如应形想制心样干都向变关问比展那它最及外没看治提五解系林者米群头意只明四道马认次文通但条较克又公孔领军流入接席位情运器并飞原油放立题质指建区验活众很教决特此常石强极土少已根共直团统式转别造切九你取西持总料连任志观调七么山程百报更见必真保热委手改管处己将修支识病象几先老光专什六型具示复安带每东增则完风回南广劳轮科北打积车计给节做务被整联步类集号列温装即毫知轴研单色坚据速防史拉世设达尔场织历花受求传口断况采精金界品判参层止边清至万确究书术状厂须离再目海交权且儿青才证低越际八试规斯近注办布门铁需走议县兵固除般引齿千胜细影济白格效置推空配刀叶率述今选养德话查差半敌始片施响收华觉备名红续均药标记难存测士身紧液派准斤角降维板许破述技消底床田势端感往神便贺村构照容非搞亚磨族火段算适讲按值美态黄易彪服早班麦削信排台声该击素张密害侯草何树肥继右属市严径螺检左页抗苏显苦英快称坏移约巴材省黑武培著河帝仅针怎植京助升王眼她抓含苗副杂普谈围食射源例致酸旧却充足短划剂宣环落首尺波承粉践府鱼随考刻靠够满夫失包住促枝局菌杆周护岩师举曲春元超负砂封换太模贫减阳扬江析亩木言球朝医校古呢稻宋听唯输滑站另卫字鼓刚写刘微略范供阿块某功套友限项余倒卷创律雨让骨远帮初皮播优占死毒圈伟季训控激找叫云互跟裂粮粒母练塞钢顶策双留误础吸阻故寸盾晚丝女散焊功株亲院冷彻弹错散商视艺灭版烈零室轻血倍缺厘泵察绝富城冲喷壤简否柱李望盘磁雄似困巩益洲脱投送奴侧润盖挥距触星松送获兴独官混纪依未突架宽冬章湿偏纹吃执阀矿寨责熟稳夺硬价努翻奇甲预职评读背协损棉侵灰虽矛厚罗泥辟告卵箱掌氧恩爱停曾溶营终纲孟钱待尽俄缩沙退陈讨奋械载胞幼哪剥迫旋征槽倒握担仍呀鲜吧卡粗介钻逐弱脚怕盐末阴丰雾冠丙街莱贝辐肠付吉渗瑞惊顿挤秒悬姆烂森糖圣凹陶词迟蚕亿矩康遵牧遭幅园腔订香肉弟屋敏恢忘编印蜂急拿扩伤飞露核缘游振操央伍域甚迅辉异序免纸夜乡久隶缸夹念兰映沟乙吗儒杀汽磷艰晶插埃燃欢铁补咱芽永瓦倾阵碳演威附牙芽永瓦斜灌欧献顺猪洋腐请透司危括脉宜笑若尾束壮暴企菜穗楚汉愈绿拖牛份染既秋遍锻玉夏疗尖殖井费州访吹荣铜沿替滚客召旱悟刺脑措贯藏敢令隙炉壳硫煤迎铸粘探临薄旬善福纵择礼愿伏残雷延烟句纯渐耕跑泽慢栽鲁赤繁境潮横掉锥希池败船假亮谓托伙哲怀割摆贡呈劲财仪沉炼麻罪祖息车穿货销齐鼠抽画饲龙库守筑房歌寒喜哥洗蚀废纳腹乎录镜妇恶脂庄擦险赞钟摇典柄辩竹谷卖乱虚桥奥伯赶垂途额壁网截野遗静谋弄挂课镇妄盛耐援扎虑键归符庆聚绕摩忙舞遇索顾胶羊湖钉仁音迹碎伸灯避泛亡答勇频皇柳哈揭甘诺概宪浓岛袭谁洪谢炮浇斑讯懂灵蛋闭孩释乳巨徒私银伊景坦累匀霉杜乐勒隔弯绩招绍胡呼痛峰零柴簧午跳居尚丁秦稍追梁折耗碱殊岗挖氏刃剧堆赫荷胸衡勤膜篇登驻案刊秧缓凸役剪川雪链渔啦脸户洛孢勃盟买杨宗焦赛旗滤硅炭股坐蒸凝竟陷枪黎救冒暗洞犯筒您宋弧爆谬涂味津臂障褐陆啊健尊豆拔莫抵桑坡缝警挑污冰柬嘴啥饭塑寄赵喊垫丹渡耳刨虎笔稀昆浪萨茶滴浅拥穴覆伦娘吨浸袖珠雌妈紫戏塔锤震岁貌洁剖牢锋疑霸闪埔猛诉刷狠忽灾闹乔唐漏闻沈熔氯荒茎男凡抢像浆旁玻亦忠唱蒙予纷捕锁尤乘乌智淡允叛畜俘摸锈扫毕璃宝芯爷鉴秘净蒋钙肩腾枯抛轨堂拌爸循诱祝励肯酒绳穷塘燥泡袋朗喂铝软渠颗惯贸粪综墙趋彼届墨碍启逆卸航衣孙龄岭骗休借".$addChars;
            break;
        default :
            // 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
            $chars='ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789'.$addChars;
            break;
    }
    if($len>10 ) {//位数过长重复字符串一定次数
        $chars= $type==1? str_repeat($chars,$len) : str_repeat($chars,5);
    }
    if($type!=4) {
        $chars   =   str_shuffle($chars);
        $str     =   substr($chars,0,$len);
    }else{
        // 中文随机字
        for($i=0;$i<$len;$i++){
          $str.= msubstr($chars, floor(mt_rand(0,mb_strlen($chars,'utf-8')-1)),1);
        }
    }
    return $str;
}

/**
 * 此功能用于id去重复
 * 加入id
 * @param unknown_type $ids
 */
  function  pidsI($ids){
  	$uid=$_SESSION['mid'];
	if(($idsold=S('page_'.$uid))!=false){
		$idsold=S('page_'.$uid);
		$newids= array_merge($ids,$idsold);
	}else{
		$newids=$ids;
	}
	S('page_'.$uid,$newids);
}
/**
 * 此功能用于id去重复
 * 取出id 对应的字符串
 * @param unknown_type $ids
 */
  function pidsO(){
  	$uid=$_SESSION['mid'];
	$ids=S('page_'.$uid);
	$idsstr= implode(',',$ids);
	if(empty($idsstr)){
		$idsstr='-1';
	}
	return ' and id not in ('.$idsstr.') ';
}

/**
 * 此功能用于id去重复
 * 清除缓存中的id
 * @param unknown_type $ids
 */
  function clearIds(){
  	$uid=$_SESSION['mid'];
  	if(($idsold=S('page_'.$uid))!=false){
  		S('page_'.$uid,null);
  	}
	
}

?>